import { getUserTempToken } from '@/utils/userTemp_token';
import { reqShopCart, reqDeleteGoods, reqCheckCart } from '@/api/index';
const actions = {
    //删除选中的商品
    deleteSelectGoods(context) {
        let promise = []
        context.getters.getCartInfoList.cartInfoList.forEach(item => {
            if (item.isChecked == 1) {
                let result = context.dispatch('getDeleteGoods', item.skuId)
                promise.push(result)
            }
        });
        return Promise.all(promise)
    },
    //全选
    shopCartCheckedAll(context, isChecked) {
        let promise = []
        let checked = isChecked ? '1' : '0'
        context.getters.getCartInfoList.cartInfoList.forEach(item => {
            //商品的选择状态跟当前不一样，发送请求
            if (item.isChecked != isChecked) {
                let result = context.dispatch('getCheckCart', { skuId: item.skuId, isChecked: checked })
                promise.push(result)
            }
        });
        return Promise.all(promise)
    },
    //切换商品的选中状态
    async getCheckCart(context, { skuId, isChecked }) {
        let result = await reqCheckCart({ skuId, isChecked })
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('filer'))
        }
    },
    //删除购物车商品
    async getDeleteGoods(context, skuId) {
        let result = await reqDeleteGoods(skuId)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('filer'))
        }
    },
    //获取用户购物车商品列表
    async getShopCartInfo(context) {
        let result = await reqShopCart()
        if (result.code == 200) {
            context.commit('GETSHOPCARTINFO', result.data)
        }
    }
}
const mutations = {
    //用户购物车商品列表
    GETSHOPCARTINFO(state, value) {
        state.shopCartInfo = value
    }
}
const state = {
    // 游客token
    userTempId: getUserTempToken(),
    //购物车商品信息
    shopCartInfo: []
}
const getters = {
    //简化购物车商品信息
    getCartInfoList(state) {
        return state.shopCartInfo[0] || {}
    }
}
export default {
    namespaced: true,// 开启命名空间
    actions, mutations, state, getters
}
